package cn.wen.core.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;

import java.io.File;

import cn.wen.base.util.AppConfig;

/**
 * 数据库操作的工厂构建
 */

public class DaoSupportFactory {
    public static final String DB_NAME = "app.db";// 数据库的名称
    public static final String DB_DIR = "database";// 数据库的目录
    private static DaoSupportFactory mFactory;
    private SQLiteDatabase mSqLiteDatabase;

    private DaoSupportFactory() {
        // 数据库的存放目录
        File dbDir = createCacheDir(AppConfig.getInstance().getContext(), DB_DIR);
        File dbFile = new File(dbDir, DB_NAME);
        if (!dbFile.exists()) {
            mSqLiteDatabase = SQLiteDatabase.openOrCreateDatabase(dbFile, null);
        } else {
            mSqLiteDatabase = SQLiteDatabase.openDatabase(dbFile.getAbsolutePath(), null, SQLiteDatabase.OPEN_READWRITE);
        }
    }

    /**
     * 创建文件目录
     */
    private File createCacheDir(Context context, String dbDir) {
        File dir = null;
        if (checkSDExist()) {
            dir = new File(context.getExternalFilesDir(null), dbDir);
        } else {
            dir = new File(context.getFilesDir(), dbDir);
        }
        if (!dir.exists()) {
            dir.mkdirs();
        }
        if (!dir.exists()) {
            return context.getFilesDir();
        }
        return dir;
    }

    // 检查是否SDK准备好
    public static boolean checkSDExist() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    public static DaoSupportFactory getFactory() {
        if (mFactory == null) {
            synchronized (DaoSupportFactory.class) {
                if (mFactory == null) {
                    mFactory = new DaoSupportFactory();
                }
            }
        }
        return mFactory;
    }

    /**
     * 获取数据库操作类
     *
     * @param <T>
     * @return
     */
    public <T> IDaoSupport<T> getDao(Class<T> clazz) {
        IDaoSupport<T> support = new DaoSupport<>();
        support.init(mSqLiteDatabase, clazz);
        return support;
    }

}
